# utils/ip_region.py

from utils.xdbSearcher import XdbSearcher

# 1. 预先加载整个 xdb
db_path = "./data/ip2region.xdb"
vector_index = None
searcher = None

def get_ip_region(ip):
    """
    返回 (region_string, 国家, 省份, 城市)
    如: ('中国|0|福建省|厦门市|移动', '中国', '福建省', '厦门市')
    """
    global vector_index, searcher
    try:
        if not vector_index:
            vector_index = XdbSearcher.loadVectorIndexFromFile(dbfile=db_path)
        if not searcher:
            searcher = XdbSearcher(dbfile=db_path, vectorIndex=vector_index)
        region = searcher.search(ip)
        parts = region.split('|')
        if len(parts) >= 5:
            return region, parts[0], parts[2], parts[3]
    except Exception as e:
        print(f"[IP解析失败] {ip} -> {e}")
    return None, '', '', ''




if __name__ == '__main__':
    get_ip_region('112.48.10.4')
    # 输出的结果为  中国|0|福建省|厦门市|移动
